# -*- coding: utf-8 -*-
#    Programmer:  D.G.J
#
"""
"""
import re, sys, time

def bin2int(s):
    r = 0
    for i in range(0,len(s)):
        r += ord(s[i])*pow(256,i)
    return r

def bin2ip(s):
    return "%d.%d.%d.%d" % ( ord(s[3]),ord(s[2]),ord(s[1]),ord(s[0]))

def int2ip(i):
    return "%d.%d.%d.%d" % (i/(256*256*256), (i%(256*256*256))/(256*256), (i%(256*256))/(256), i%256)

def ip2int(ip):
    m = re.match('^(\d+)\.(\d+)\.(\d+)\.(\d+)$',ip)
    if not m:
        return 0
    else:
        return int(m.group(1))*256*256*256+int(m.group(2))*256*256+int(m.group(3))*256+int(m.group(4));

def ip2loc(ip):
    ip = ip2int(ip)
    if not ip:
        return "invalid ip"
    f = open('qqwry.dat','rb')

    index_begin = bin2int(f.read(4))
    index_end   = bin2int(f.read(4))

    a = 0
    b = (index_end-index_begin)/7
    found = 0

    while(b>=a):
        c = (a+b)/2
        f.seek(index_begin+c*7)
        ip1 = bin2int(f.read(4))
        if ip1 <= ip:
            f.seek(index_begin+c*7+7)
            ip2 = bin2int(f.read(4))
            if ip2 > ip:
                f.seek(index_begin+c*7+4)
                found = bin2int(f.read(3))
                break;
            else:
                a = c + 1
        else:
            b = c - 1
    if not found:
        f.close()
        return "not found"

    ip1 = int2ip(ip1)
    f.seek(found)
    ip2 = bin2ip(f.read(4))
    loc1,loc2 = get_loc(f,found+4)
    f.close()
    return "(%s-%s) %s %s" % ( ip1,ip2,loc1.decode('gb2312').encode('utf-8'),loc2.decode('gb2312').encode('utf-8'))

def get_loc(f,idx):
    loc1 = ""
    loc2 = ""

    f.seek(idx)
    c = f.read(1)
    if ord(c) == 1:
        idx = bin2int(f.read(3))
        f.seek(idx)
        c = f.read(1)

    idx2 = 0
    if ord(c) == 2:
        idx2 = idx+4
        idx = bin2int(f.read(3))
        f.seek(idx)
        c = f.read(1)

    while(ord(c)):
        loc1 += c
        c = f.read(1)

    if idx2:
        f.seek(idx2)

    c = f.read(1)
    if ord(c) == 2:
        idx = bin2int(f.read(3))
        f.seek(idx)
        c = f.read(1)

    while(ord(c)):
        loc2 += c
        c = f.read(1)
    return (loc1,loc2)

if __name__ == "__main__":

    count = 10000
    t = time.time()*1000000
    for x in range(1,count+1):
        lst = [str(x%254), str(x%253), str(x%252), str(x%251),]
        #print '.'.join(lst)
        #print ip2loc('.'.join(lst))
        ip2loc('.'.join(lst))
    print 'timecost:', (time.time()*1000000 - t)/count

    #print bin2int('\x00\x00\x00\xff')
    #print bin2ip('\x00\x00\x00\xff')
    #print int2ip(4278190080)
    #print ip2int('255.0.0.0')
    #print ip2loc(sys.argv[1])
    #ret = ip2loc('202.102.249.68')
    #retlist = ret.split(' ')
    #location = retlist[1].decode('gb2312').encode('utf-8')
    #print retlist[1], location
